const app = getApp();

function onReachBottom() {
  const that = this;
  console.log("onReachBottom")
  that.getPageList(true);
}

function listDataInit() {
  const that = this;
  that.setData({
    keyword: '', //搜索框输入值
    // lists: [], //列表数据
    msg: '请稍等...', //提示信息
    footMsg: "没有更多数据啦！", //底部提示信息
    page: 1, //当前页数
    row: 10, //1页的条数
    isReach: false, //是否全部加载完毕
  })
  that.getPageList();
  return true;
}

function getListParams() {
  const that = this;
  var row = that.data.row || 10;
  var page = that.data.page || 1;
  var keyword = that.data.keyword;

  return {
    pageSize: row,
    pageNum: page,
    keyword: keyword,
  }
}

/**
 * 获取列表
 * param isReachBottom [Boolean] 是否上拉加载触发
 */
function getPageList(isReachBottom) {
  var that = this;
  var lists = that.data.lists;
  var row = that.data.row;
  var page = that.data.page;
  var keyword = that.data.keyword;
  var isReach = that.data.isReach;
  var footMsg = "";

  if (isReachBottom) {
    if (isReach) return false;
    page++;
  }

  if (page == 1) {
    lists = [];
  }

  var reqData = that.getListParams();

  app.middleware.requestAjax({
    serAddr: that.reqUrl,
    data: reqData,
    cancelToast: true,
    success: function(res) {
      console.log(res)
      var tempLists = res.data || [];

      if (row <= tempLists.length) {
        isReach = false;
        footMsg = "上拉加载更多";
      } else {
        isReach = true;
        footMsg = "没有更多数据啦！";
      }
      that.setData({
        msg: "",
        page: page,
        lists: lists.concat(tempLists),
        isReach: isReach,
        footMsg: footMsg,
      })
    },
    fail: function(res) {

      if (isReachBottom) {
        that.setData({
          footMsg: res && res.msg || "加载失败",
        })
      } else {
        that.setData({
          msg: res && res.msg || "加载失败",
        })
      }

    }
  })
}

export default {
  onReachBottom,
  listDataInit,
  getListParams,
  getPageList,
}